package com.yt.product.api.cms;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import com.yt.product.models.bo.ProductInfoBO;
import com.yt.product.models.bo.ProductInfoDeleteRequest;
import com.yt.product.models.bo.ProductInfoSaveBO;
import com.yt.product.models.bo.ProductStatusUpdateRequest;
import com.yt.product.models.dto.ProductInfoDTO;
import com.yt.product.models.service.IProductInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * 产品信息控制器
 *
 * @author lianyadong
 * @Date 2025-09-03 14:14:54
 */

@RestController
@RequestMapping("/cms/productInfo")
@Slf4j
@Api(value = "ProductInfoController",tags = "产品信息接口")
public class ProductInfoController {

    @DubboReference
    private IProductInfoService productInfoService;

    @ApiOperation(value = "添加产品信息", notes = "添加产品信息")
    @PostMapping("/insert")
    public Result insert(@RequestBody ProductInfoSaveBO saveBO) {
        try {
            // 如果ID为空，则生成10位随机数字ID
            if (saveBO.getId() == null) {
                saveBO.setId(generateRandomId());
            }
            log.info("开始添加产品信息: id={}, productName={}", saveBO.getId(), saveBO.getProductName());

            boolean flag = productInfoService.add(saveBO);
            if (flag) {
                log.info("产品信息添加成功: id={}", saveBO.getId());
                return new Result<>();
            } else {
                log.error("产品信息添加失败: id={}", saveBO.getId());
                return new Result<>(CodeEnum.FAIL_100007, "产品信息添加失败");
            }
        } catch (Exception e) {
            log.error("添加产品信息异常：saveBO={}", saveBO, e);
            return new Result<>(CodeEnum.FAIL_100005, "服务器繁忙，请稍后重试");
        }
    }
    //生成10位随机数字ID
    private Long generateRandomId() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        // 第一位数字（1-9），确保是10位数
        sb.append(random.nextInt(9) + 1);
        // 后9位数字（0-9）
        for (int i = 0; i < 9; i++) {
            sb.append(random.nextInt(10));
        }
        return Long.parseLong(sb.toString());
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存产品信息",notes = "保存产品信息")
    public Result save(ProductInfoSaveBO saveBO){
        if(saveBO.getId() == null){
            //添加
            return  insert(saveBO);
        } else {
            return  update(saveBO);
        }
    }

    @ApiOperation(value = "修改产品信息", notes = "修改产品基础信息")
    @PostMapping("/update")
// 关键：添加 @RequestBody，确保前端 JSON 参数能正确绑定到 BO
    public Result update(@RequestBody ProductInfoSaveBO saveBO) {
        try {
            if (saveBO.getId() == null) {
                log.error("修改产品失败：产品ID为空");
                return new Result<>(CodeEnum.FAIL_100002, "产品ID不能为空");
            }

            ProductInfoDTO dto = new ProductInfoDTO();
            BeanUtils.copyProperties(saveBO, dto);
            dto.setUpdateTime(new Date());

            boolean flag = productInfoService.updateById(dto);
            if (flag) {
                return new Result<>("修改成功");
            } else {
                return new Result<>(CodeEnum.FAIL_100008, "修改失败，产品不存在或已删除");
            }

        } catch (Exception e) {
            log.error("修改产品异常：saveBO={}", saveBO, e);
            return new Result<>(CodeEnum.FAIL_100005, "服务器繁忙，请稍后重试");
        }
    }

    @PostMapping("/updateStatus")
    @ApiOperation(value = "修改状态", notes = "修改状态")
    public Result updateStatus(@Valid @RequestBody ProductStatusUpdateRequest request) {
        ProductInfoDTO dto = new ProductInfoDTO();
        dto.setId(request.getId());
        dto.setStatus(request.getStatus());
        boolean flag = productInfoService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除产品信息", notes = "删除产品信息")
    public Result delete(@Valid @RequestBody ProductInfoDeleteRequest request) {
        boolean flag = productInfoService.deleteById(request.getId());
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @PostMapping("/deleteBatch")
    @ApiOperation(value = "批量删除产品信息",notes = "批量删除产品信息")
    @ApiImplicitParam(name = "ids",value = "ids:以逗号隔开",required = true,paramType = "query", dataType = "String")
    public Result deleteBatch(@RequestParam("ids") String ids){
        if(StrUtils.isEmpty(ids)){
            return new Result(CodeEnum.FAIL_100002 );
        }
        String[] arr = ids.split(",");
        productInfoService.deleteBatchIds(Arrays.asList(arr));
        return new Result<>();
    }

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找（含分类+供应商）", notes = "根据ID查询产品，包含分类名称和供应商名称")
    @ApiImplicitParam(name = "id", value = "产品ID", required = true, paramType = "query", dataType = "Long")
    public Result<ProductInfoDTO> get(@RequestParam("id") Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        // 调用关联查询方法，替换默认selectById
        ProductInfoDTO dto = productInfoService.getByIdWithRelation(id);
        return new Result<>(dto);
    }

    @ApiOperation(value = "产品信息列表（关联分类+供应商）", notes = "分页查询产品，支持状态、时间范围筛选，关联显示类型和供应商名称")
    @PostMapping("/queryPageList")
    public Result<Page<ProductInfoDTO>> queryPageList(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestBody(required = false) ProductInfoBO bo) {
        // 1. 校验分页参数
        int validPageNo = Math.max(pageNo, 1);
        int validPageSize = Math.min(Math.max(pageSize, 1), 100);
        Page<ProductInfoDTO> page = new Page<>(validPageNo, validPageSize);

        // 2. 如果有ID参数，则进行精确查询
        if (bo != null && bo.getId() != null) {
            ProductInfoDTO dto = productInfoService.getByIdWithRelation(bo.getId());
            Page<ProductInfoDTO> resultPage = new Page<>(validPageNo, validPageSize);
            if (dto != null) {
                List<ProductInfoDTO> records = new ArrayList<>();
                records.add(dto);
                resultPage.setRecords(records);
                resultPage.setTotal(1);
            } else {
                resultPage.setRecords(new ArrayList<>());
                resultPage.setTotal(0);
            }
            return new Result<>(resultPage);
        }

        // 3. 构建查询条件
        EntityWrapper<ProductInfoDTO> wrapper = new EntityWrapper<>();
        if (bo != null) {
            // 添加对产品名称精确查询的支持
            if (bo.getProductName() != null && !bo.getProductName().trim().isEmpty()) {
                wrapper.eq("product_name", bo.getProductName().trim());
            }
            // 添加对产品名称模糊查询的支持
            if (bo.getKeyword() != null && !bo.getKeyword().trim().isEmpty()) {
                wrapper.like("product_name", bo.getKeyword().trim());
            }
            if (bo.getStatus() != null) {
                wrapper.eq("status", bo.getStatus());
            }
            if (bo.getStartDate() != null) {
                wrapper.ge("create_time", bo.getStartDate());
            }
            if (bo.getEndDate() != null) {
                wrapper.le("create_time", bo.getEndDate());
            }
        }
        // 默认不查询已删除的产品（状态≠2）
        wrapper.ne("status", 2);

        // 4. 调用Service的关联查询方法
        Page<ProductInfoDTO> resultPage = productInfoService.queryProductWithRelation(page, bo);

        return new Result<>(resultPage);
    }
}

